package com.travelsky.client;

import java.awt.Font;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.util.prefs.Preferences;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

import com.travelsky.server.vo.group.ProjectGroup;
import com.travelsky.server.vo.group.User;


public class Client_enterFrame extends JFrame implements ActionListener, KeyListener {
	
	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = -2311923104492535866L;
	
	/**
	 * 登录按钮
	 */
	private JButton jbt_enter;
	
	/**
	 * 退出按钮
	 */
	private JButton jbt_exit;
	
	/**
	 * 开机自启动
	 */
	private JCheckBox jcb_autoRun;
	
	/**
	 * 文件选择器  
	 */
	public JFileChooser jfc;
	
	/**
	 * 客户端对象
	 */
	private Client client;
	
	private JComboBox<String> jcmb_group;
	private JComboBox<String> jcmb_user;
	private Preferences prefer;

	/**
	 * 构造方法
	 ******************************************
	 * @author HuangFeng [2017年7月5日 下午12:36:15]
	 * @version 1.0
	 ******************************************
	 * @param client 客户端对象
	 */
	public Client_enterFrame(Client client) {
		this.client = client;
		this.prefer = Preferences.userNodeForPackage(this.getClass()); //得到用户配置节点
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (ClassNotFoundException e1) {
			e1.printStackTrace();
		} catch (InstantiationException e1) {
			e1.printStackTrace();
		} catch (IllegalAccessException e1) {
			e1.printStackTrace();
		} catch (UnsupportedLookAndFeelException e1) {
			e1.printStackTrace();
		}
		Image image = new ImageIcon(getClass().getResource("icon.jpg")).getImage();
		setIconImage(image);
		setTitle("代码提交工具"+client.version);
		getContentPane().setLayout(null);
		setSize(296, 249);
		WinCenter.center(this);
		setResizable(false);
		addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				jbt_exit.doClick();
			}
			@Override
			public void windowOpened(WindowEvent e) {
	              jbt_enter.requestFocus();
	       }
		});
		jcb_autoRun = new JCheckBox();
		jcb_autoRun.setText("开机自启动");
		jcb_autoRun.setBounds(1, 4, 100, 20);
		jcb_autoRun.setSelected(true);
		getContentPane().add(jcb_autoRun);
		
		JLabel lblNewLabel = new JLabel("项目组");
		lblNewLabel.setFont(new Font("宋体", Font.PLAIN, 14));
		lblNewLabel.setBounds(23, 40, 81, 34);
		getContentPane().add(lblNewLabel);

		jcmb_group=new JComboBox<>();
		if(client.projectGroupList == null){
			closeClient("连接服务器失败");
		}
		for (ProjectGroup projectGroup : client.projectGroupList) {
			jcmb_group.addItem(projectGroup.getName());
		}
		jcmb_group.setBounds(90, 40, 170, 34);
		jcmb_group.addActionListener(this);
		getContentPane().add(jcmb_group);

		JLabel lblNewLabel_1 = new JLabel("姓名");
		lblNewLabel_1.setFont(new Font("宋体", Font.PLAIN, 14));
		lblNewLabel_1.setBounds(23, 100, 81, 34);
		getContentPane().add(lblNewLabel_1);

		jcmb_user = new JComboBox<>();
		for (User user : client.projectGroupList.get(0).getUsers()) {
			jcmb_user.addItem(user.getName());
		}
		jcmb_user.setBounds(90, 100, 170, 34);
		getContentPane().add(jcmb_user);

		jbt_enter = new JButton("登录");
		jbt_enter.addActionListener(this);
		jbt_enter.addKeyListener(this);
		jbt_enter.setFont(new Font("宋体", Font.PLAIN, 14));
		jbt_enter.setBounds(23, 162, 108, 39);
		getContentPane().add(jbt_enter);

		jbt_exit = new JButton("退出");
		jbt_exit.setFont(new Font("宋体", Font.PLAIN, 14));
		jbt_exit.setBounds(144, 162, 113, 39);
		jbt_exit.addActionListener(this);
		getContentPane().add(jbt_exit);
		
		setDefaultInfo();//设置默认项目组
	}

	/**
	 * 设置默认项目组，姓名
	 ******************************************
	 * @author HuangFeng [2017年10月29日 下午1:00:31]
	 * @version 1.0
	 ******************************************
	 */
	private void setDefaultInfo() {
		String groupName = prefer.get("groupName", "");
		String username = prefer.get("username", "");
		if(!groupName.isEmpty() && !username.isEmpty()){
			if(!groupName.equals(jcmb_group.getSelectedItem().toString())){
				for (int i = 0; i < jcmb_group.getItemCount(); i++) {
					//注册表中得到的项目组在下拉列表中
					if(groupName.equals(jcmb_group.getItemAt(i))){
						jcmb_group.setSelectedItem(groupName);
						changeGroup(groupName);
						break;
					}
				}
			}
			if(!username.equals(jcmb_user.getSelectedItem().toString())){
				for (int i = 0; i < jcmb_user.getItemCount(); i++) {
					//注册表中得到的用户名在下拉列表中
					if(username.equals(jcmb_user.getItemAt(i))){
						jcmb_user.setSelectedItem(username);
						break;
					}
				}
			}
		}
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == jbt_exit) {
			setVisible(false);
			client.exitLogin();
		}
		else if (e.getSource() == jbt_enter) {
			String groupName = jcmb_group.getSelectedItem().toString();
			String username = jcmb_user.getSelectedItem().toString();
			changeStart(jcb_autoRun.isSelected());
			saveInfoToRegedit(groupName,username);
			client.login(groupName, username);
		}else if(e.getSource() == jcmb_group){
			String groupName=(String)jcmb_group.getSelectedItem();
			changeGroup(groupName);
		}
	}

	/**
	 * 切换项目组，实现用户联动
	 ******************************************
	 * @author HuangFeng [2017年10月29日 下午1:18:52]
	 * @version 1.0
	 ******************************************
	 * @param groupName 项目组
	 */
	private void changeGroup(String groupName) {
		for (ProjectGroup projectGroup : client.projectGroupList) {
			if(projectGroup.getName().equals(groupName)){
				jcmb_user.removeAllItems();
				for (User user : projectGroup.getUsers()) {
					jcmb_user.addItem(user.getName());
				}
			}
		}
	}

	/**
	 * 保存用户信息到注册表
	 ******************************************
	 * @author HuangFeng [2017年10月29日 下午12:04:01]
	 * @version 1.0
	 ******************************************
	 */
	private void saveInfoToRegedit(String groupName, String username) {
		prefer.put("groupName",groupName);
		prefer.put("username",username);
	}

	/**
	 * 开机自启动
	 ******************************************
	 * @author HuangFeng [2017年10月13日 上午9:40:51]
	 * @version 1.0
	 ******************************************
	 * @param selected true/false
	 */
	public void changeStart(boolean isStartAtLogon){
		String regKey = "HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run";
		String myAppName = "代码提交工具";
		String exePath = new File("").getAbsolutePath()+"\\"+myAppName+client.version+".exe";
		try {
			Runtime.getRuntime().exec("reg "+"delete "+regKey+" /v "+myAppName+" /f");
			if(isStartAtLogon){
				Runtime.getRuntime().exec("reg "+"add "+regKey+" /v "+myAppName+" /t reg_sz /d "+exePath);
				//Runtime.getRuntime().exec("reg "+(isStartAtLogon?"add ":"delete ")+regKey+" /v "+myAppName+(isStartAtLogon?" /t reg_sz /d "+exePath:" /f"));
			}
			//关闭注册表进程
			Runtime.getRuntime().exec("taskkill /f /t /im reg.exe");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 下载新版本，选择文件目录
	 ******************************************
	 * @author HuangFeng [2017年10月20日 下午5:09:21]
	 * @version 1.0
	 ******************************************
	 * @param updaeMessage 更新日志
	 * @return 选择的磁盘目录
	 */
	public String chooseFolder(String updaeMessage){
		JOptionPane.showMessageDialog(this, "检测到您的版本不是最新的，点击确认下载最新版本\n"+updaeMessage);
		jfc = new JFileChooser(".");
		jfc.setFileSelectionMode(1);// 设定只能选择到文件夹
		int state = jfc.showOpenDialog(null);// 此句是打开文件选择器界面的触发语句  
        if (state == 1) {  
            return "";
        } else {
            File f = jfc.getSelectedFile();// f为选择到的目录  
            return f.getAbsolutePath();
        }  
	}
	
	/**
	 * 关闭客户端
	 ******************************************
	 * @author HuangFeng [2017年7月5日 下午12:31:19]
	 * @version 1.0
	 ******************************************
	 * @param message 消息
	 */
	public void closeClient(String message) {
		JOptionPane.showMessageDialog(this, message , "提示", JOptionPane.OK_OPTION);
		setVisible(false);
		client.exitClient();
	}
	
	@Override
	public void keyPressed(KeyEvent arg0) {
		if (arg0.getKeyCode() == KeyEvent.VK_ENTER) {
			jbt_enter.doClick();
		}
	}

	@Override
	public void keyReleased(KeyEvent arg0) {
	}

	@Override
	public void keyTyped(KeyEvent arg0) {
	}
	
}
